package com.cloudlead.fleetAction.service.impl;

import com.cloudlead.common.lang.persistence.*;
import com.cloudlead.commonData.service.*;
import com.cloudlead.commonData.vo.*;
import com.cloudlead.fleetAction.service.ContainerSer;
import com.cloudlead.fleetService.vo.ContainerVo;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 20150817 on 2015/9/1.
 */
@Service
public class ContainerSerImpl implements ContainerSer{
    @Autowired
    TbContainerInfoService containerService;
    @Autowired
    TbCustomerOrderService tbCustomerOrderService;
    @Autowired
    TbFleetOrderService tbFleetOrderService;
    @Autowired
    BaseCompanyService baseCompanyService;
    @Autowired
    BaseVoyageService baseVoyageService;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat sdfTime=new SimpleDateFormat("yy-MM-dd HH:mm:ss");

    @Override
    public Page<ContainerVo> findAllContainer(ContainerVo vo, int page, int size) {
        ContainerVo cto = new ContainerVo();
        if(vo!=null){//如果vo不为空
            cto=vo;
        }
        PageRequest pr = new PageRequest();
        List<Term> tr = new ArrayList<Term>();

        tr.add(new Term("flag","0"));//未删除
        if (cto.getContainerNo()!=null&&!cto.getContainerNo().equals("")) {
            tr.add(new Term("containerNo",Operator.LK,"%"+cto.getContainerNo()+"%"));//箱号
        }
        if (cto.getTbCustomerOrder()!= null&&!cto.getTbCustomerOrder().equals("")) {
            tr.add(new Term("tbCustomerOrder.id", cto.getTbCustomerOrder()));//订单ID
        }
        if (cto.getFleetorderid()!= null&&!cto.getFleetorderid().equals("")) {
            tr.add(new Term("fleetOrder.id", cto.getFleetorderid()));//车队订单ID
        }
        if (cto.getIsStart()!=null&&!cto.getIsStart().equals("")) {
            tr.add(new Term("fleetOrder.isStart", cto.getIsStart()));//进出口
        }
        if(cto.getOrderType()!=null&&!cto.getOrderType().equals("")){//类型
            tr.add(new Term("fleetOrder.orderType",cto.getOrderType()));
        }
        if(cto.getCustomerCode()!=null&&!cto.getCustomerCode().equals("")){//类型
            tr.add(new Term("fleetOrder.customerCode",cto.getCustomerCode()));
        }
        if(cto.getTrackNo() !=null && !cto.getTrackNo().equals("")){//运单号
            tr.add(new Term("tbCustomerOrder.bussinessCode",Operator.LK,"%"+cto.getTrackNo()+"%"));
        }
        if(cto.getFleetId() != null&& !cto.getFleetId().equals("")){
            tr.add(new Term("fleetOrder.fleetCompanyId",cto.getFleetId()));
        }
        if (cto.getBussinessCode()!=null &&!cto.getBussinessCode().equals("")){
            tr.add(new Term("tbCustomerOrder.bussinessCode",cto.getBussinessCode()));
        }
       /* if(cto.getOrderBussinessCode()!=null &&!cto.getOrderBussinessCode().equals("")){
            tr.add(new Term("fleetOrder.bussinessCode",cto.getOrderBussinessCode()));
        }*/
        if(cto.getPlanDate()!=null&&!cto.getPlanDate().equals("")){
            try {
                tr.add(new Term("planDate",Operator.GE,sdf.parse(cto.getPlanDate())));//string 转换 date
                Calendar cal = Calendar.getInstance();
                cal.setTime(sdf.parse(cto.getPlanDate()));
                cal.add(Calendar.DATE, 1);
                tr.add(new Term("planDate",Operator.LT,cal.getTime()));
            }catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        /*
        List<Term> trFleetOrder = new ArrayList<Term>();
        //装箱地点模糊查询
        if(cto.getPackagingAddress()!=null&&!cto.getPackagingAddress().equals("")) {
            trFleetOrder.add(new Term("packagingAddress", Operator.LK, "%" + cto.getPackagingAddress() + "%"));
        }
        //卸箱地点模糊查询
        if(cto.getRemoveAddress()!=null&&!cto.getRemoveAddress().equals("")) {
            trFleetOrder.add(new Term("removeAddress", Operator.LK, "%" + cto.getRemoveAddress() + "%"));
        }
        //起始港模糊查询
        if(cto.getPolName()!=null&&!cto.getPolName().equals("")) {
            trFleetOrder.add(new Term("polName", Operator.LK, "%" + cto.getPolName() + "%"));
        }
        //目的港模糊查询
        if(cto.getDelName()!=null&&!cto.getDelName().equals("")) {
            trFleetOrder.add(new Term("delName", Operator.LK, "%" + cto.getDelName() + "%"));
        }
        if (trFleetOrder.size()>0){
            trFleetOrder.add(new Term("fleetCompanyId",cto.getFleetId()));
            Filter filter =new Filter(new Criteria(trFleetOrder));
            List<TbFleetOrder> flList=tbFleetOrderService.list(filter,null);
            List boIdList= new ArrayList<>();
            for(TbFleetOrder bo:flList) {
                boIdList.add(bo.getId());
            }
            tr.add(new Term("fleetOrder.id", Operator.IN, boIdList));
        }
       */
        //装箱地点模糊查询
        if(cto.getPackagingAddress()!=null&&!cto.getPackagingAddress().equals("")) {
            tr.add(new Term("fleetOrder.packagingAddress", Operator.LK, "%" + cto.getPackagingAddress() + "%"));
        }
        //卸箱地点模糊查询
        if(cto.getRemoveAddress()!=null&& !cto.getRemoveAddress().equals("")) {
            tr.add(new Term("fleetOrder.removeAddress", Operator.LK, "%" + cto.getRemoveAddress() + "%"));
        }
        //起始港模糊查询
        if(cto.getPolName()!=null&& !cto.getPolName().equals("")) {
            tr.add(new Term("fleetOrder.polName", Operator.LK, "%" + cto.getPolName() + "%"));
        }
        //目的港模糊查询
        if(cto.getDelName()!=null&& !cto.getDelName().equals("")) {
            tr.add(new Term("fleetOrder.delName", Operator.LK, "%" + cto.getDelName() + "%"));
        }
        //车队名称模糊查询
        if(cto.getFleetName() != null&& !cto.getFleetName().equals("")){
            List<Term> tr1 = new ArrayList<Term>();
            tr1.add(new Term("companyName",Operator.LK,"%"+cto.getFleetName()+"%"));
            Filter filter =new Filter(new Criteria(tr1));
            List<BaseCompany> flList=baseCompanyService.list(filter,null);
            List boIdList= new ArrayList<>();
            for(BaseCompany bo:flList) {
                boIdList.add(bo.getId());
            }
            tr.add(new Term("fleetOrder.fleetCompanyId", Operator.IN, boIdList));
        }
        //按船名模糊查询车队订单
        List<Term> trVoyage = new ArrayList<Term>();
        if(cto.getVessel() != null&& !cto.getVessel().equals("")) {
            trVoyage.add(new Term("vessel", Operator.LK, "%" + cto.getVessel() + "%"));
        }
        if(cto.getVoyage() != null&& !cto.getVoyage().equals("")) {
            trVoyage.add(new Term("voyage", Operator.LK, "%" + cto.getVoyage() + "%"));
        }
        if(cto.getArriveExpectedTime()!=null&&!cto.getArriveExpectedTime().equals("")) {
            try {
                trVoyage.add(new Term("arriveExpectedTime",sdf.parse(cto.getArriveExpectedTime())));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if(cto.getStartExpectedTime()!=null&&!cto.getStartExpectedTime().equals("")){
            try {
                trVoyage.add(new Term("startExpectedTime",sdf.parse(cto.getStartExpectedTime())));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (trVoyage.size()>0){
            Filter filter =new Filter(new Criteria(trVoyage));
            List<BaseVoyage> bv=baseVoyageService.list(filter,null);
            List boIdList= new ArrayList<>();
            for(BaseVoyage bo:bv) {
                boIdList.add(bo.getId());
            }
            tr.add(new Term("fleetOrder.baseVoyage.id", Operator.IN, boIdList));
        }
        //船东名称模糊查询
        if(cto.getShipName() != null&& !cto.getShipName().equals("")){
            List<Term> tr1 = new ArrayList<Term>();
            tr1.add(new Term("companyName",Operator.LK,"%"+cto.getShipName()+"%"));
            Filter filter =new Filter(new Criteria(tr1));
            List<BaseCompany> flList=baseCompanyService.list(filter,null);
            List boIdList= new ArrayList<>();
            for(BaseCompany bo:flList) {
                boIdList.add(bo.getId());
            }
            String fld=cto.getIsStart()==0?"dest_company_id":"base_company_id";
            tr.add(new Term("tbCustomerOrder."+fld, Operator.IN, boIdList));
        }
        String theState = "fleetStatus";
        Filter filter =null;
        if(cto.getState().equals("未执行")) {//未派
            tr.add(new Term(theState,"未派车"));
            filter = new Filter(new Criteria(tr));
        }else if (cto.getState().equals("已执行")){//在运
            List list = new ArrayList<>();
            list.add("已派车");
            list.add("已拆箱");
            list.add("已装箱");
            list.add("已提箱");
            tr.add(new Term(theState,Operator.IN,list));

            filter = new Filter(new Criteria(tr));
        }else if (cto.getState().equals("已完成")){//已完成

            tr.add(new Term(theState,cto.getState()));
            filter = new Filter(new Criteria(tr));
        }else{
             filter = new Filter(new Criteria(tr));
        }

        pr.setPage(page);
        pr.setSize(size);
        pr.setFilter(filter);


        Page<TbContainerInfo> pb =containerService.findAll(pr);
        List<TbContainerInfo> lx1 = new ArrayList<TbContainerInfo>();

        for(Iterator<TbContainerInfo> it = pb.iterator();it.hasNext();) {//遍历
            TbContainerInfo tci = it.next();
            if(tci.getTbCustomerOrder()!=null&&tci.getTbCustomerOrder().getId()!=null){//订单ID不为空
                TbCustomerOrder tco= tbCustomerOrderService.view(tci.getTbCustomerOrder().getId());//查出订单信息
                tci.setTbCustomerOrder(tco);
                if (tci.getFleetOrder()!=null) {
                    TbFleetOrder tfo = tbFleetOrderService.view(tci.getFleetOrder().getId());
                    tci.setFleetOrder(tfo);
                }
            }
            lx1.add(tci);
        }

        pb.setContent(lx1);

      //  System.out.println("===================="+pb.getContent().get(0).getTbCustomerOrder().getsDo().getName());

        Page<ContainerVo> pbv = new Page<>();
        BeanUtils.copyProperties(pb,pbv);
        return pbv;
    }

    @Override
    public void addOrderCon(ContainerVo vo) {
        TbContainerInfo tci = new TbContainerInfo();
        BeanUtils.copyProperties(vo, tci);
        tci.setFlag("0");
        tci.setFleetStatus("未派车");
        if (vo.getPlanDate()!=null && !vo.getPlanDate().equals("")){
            tci.setPlanDate(StrToDateTime(vo.getPlanDate()));
        }
        if(vo.getFleetorderid()!=null&&!vo.getFleetorderid().equals("")){
            TbFleetOrder tbFleetOrder = new TbFleetOrder();
            tbFleetOrder.setId(vo.getFleetorderid());
            tci.setFleetOrder(tbFleetOrder);
            tci.setIsStart(tbFleetOrder.getIsStart());
        }
        containerService.create(tci);
    }

    @Override
    public void updateOrderCon(ContainerVo vo) {
        TbContainerInfo tci = containerService.view(vo.getId());
        BeanUtils.copyProperties(vo, tci);
        tci.setFlag("0");
        if (vo.getPlanDate()!=null && !vo.getPlanDate().equals("")){
            tci.setPlanDate(StrToDateTime(vo.getPlanDate()));
        }
        if(vo.getFleetorderid()!=null&&!vo.getFleetorderid().equals("")){
            TbFleetOrder tbFleetOrder = new TbFleetOrder();
            tbFleetOrder.setId(vo.getFleetorderid());
            tci.setFleetOrder(tbFleetOrder);
        }
        containerService.update(tci);
    }

    @Override
    public void deleteOrderCon(String id) {
        TbContainerInfo tci = containerService.view(id);
        tci.setFlag("1");
        containerService.update(tci);
    }

    private DateTime StrToDateTime(String sDate){
        Date d= null;
        try {
            d = sdfTime.parse(sDate);//string 转换 date
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new DateTime(d);//date 转换 dateTime 保存
    }
}
